<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import Graphic from '@arcgis/core/Graphic'
import { Delete } from '@element-plus/icons-vue'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import SimpleMarkerSymbol from '@arcgis/core/symbols/SimpleMarkerSymbol'
import SimpleLineSymbol from '@arcgis/core/symbols/SimpleLineSymbol'
import { ElMessage } from 'element-plus'
import gaodeLayer from '@/utils/GaoDeBaseLayer'
import SketchViewModel from '@arcgis/core/widgets/Sketch/SketchViewModel'
import GraphicsLayer from '@arcgis/core/layers/GraphicsLayer'

import PictureMarkerSymbol from '@arcgis/core/symbols/PictureMarkerSymbol'
import {
  facilityPointSymbol,
  scenicPointSymbol,
  viewScenicSpotSymbol,
  serviceSymbol,
  monitorSymbol,
  trafficSymbol,
  greenSymbol
} from '@/utils/facilityIcons'
// 状态变量
const mapContainer = ref<HTMLDivElement>()
const dialogVisible = ref(false)
const isAdding = ref(false)
const isDrawing = ref(false)
const editMode = ref<'add' | 'edit'>('add')
const activeTab = ref('facility') // 'facility' 或 'road'
let currentFeature: __esri.Graphic | null = null
let tempGraphic: __esri.Graphic | null = null

// 设施类型选项
const facilitytypeOptions = [
  { value: '驿站', label: '驿站' },
  { value: '景点', label: '景点' },
  { value: '餐饮', label: '餐饮' },
]

// 设施表单数据
const facilityForm = ref({
  facilityname: '',
  facilitytype: '',
  FacilityImage: '',
  FacilityIntroduction: '',
  Status: '',
  // 驿站专用字段
  serviceTime: '',
  equipmentStatus: '',
  // 景点专用字段
  parkingSpaces: '',
  chargingPiles: '',
  // 餐饮专用字段
  businessInfo: '',
  contactInfo: '',
  rating: '',
  // 存储额外信息的JSON字段
  OtherJson: '',
})

// 表单规则
const facilityRules = {
  facilityname: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  facilitytype: [{ required: true, message: '请选择设施类型', trigger: 'blur' }],
}

// 使用统一的设施图标符号（已从 facilityIcons.ts 导入）
// 创建点符号
const pointSymbol = new SimpleMarkerSymbol({
  style: 'circle',
  color: [41, 128, 185, 1],
  size: 8,
  outline: {
    color: [255, 255, 255, 1],
    width: 1,
  },
})
// 创建道路线符号
const roadSymbol = new SimpleLineSymbol({
  color: [0, 122, 194, 0.8],
  width: 4,
  style: 'solid',
  cap: 'round',
  join: 'round',
})

// 创建设施图层
const facilityLayer = new FeatureLayer({
  url: 'https://services.arcgis.com/cxicHGWOCJwYXasp/arcgis/rest/services/Facility/FeatureServer/0',
  outFields: ['*'],
  renderer: {
    type: 'unique-value', // 修改为unique-value类型
    field: 'facilitytype', // 指定用于分类的字段
    defaultSymbol: facilityPointSymbol,
    uniqueValueInfos: [
      {
        value: '驿站',
        symbol: scenicPointSymbol,
      },
      {
        value: '景点',
        symbol: viewScenicSpotSymbol,
      },
      {
        value: '餐饮',
        symbol: facilityPointSymbol,
      },
    ],
  } as never,
})
console.log(facilityLayer)

// 创建道路图层
const roadLayer = new FeatureLayer({
  url: 'https://www.geosceneonline.cn/server/rest/services/Hosted/S103/FeatureServer/0',
  outFields: ['*'],
  renderer: {
    type: 'simple',
    symbol: roadSymbol,
  } as never,
})

// 创建临时图形图层
const sketchLayer = new GraphicsLayer({
  title: '绘图图层',
})

// 创建地图
const map = new Map({
  basemap: {
    baseLayers: [gaodeLayer],
  },
})
map.add(roadLayer)
map.add(facilityLayer)
map.add(sketchLayer)

// 创建地图视图
const view = new MapView({
  map: map,
  center: [117.14435714426122, 36.29746937366678],
  zoom: 10,
})

// 图片上传相关方法
const handleImageUpload = (fileInfo: any) => {
  const file = fileInfo.raw // 获取原始文件对象
  if (!file) return

  const reader = new FileReader()
  reader.onload = (e) => {
    if (activeTab.value === 'facility') {
      facilityForm.value.FacilityImage = e.target?.result as string
    }
  }
  reader.readAsDataURL(file)
  return false
}

// 创建SketchViewModel
let sketchViewModel: __esri.SketchViewModel


// 添加设施
const addFacility = () => {
  activeTab.value = 'facility'
  isAdding.value = true
  isDrawing.value = true
  editMode.value = 'add'

  facilityForm.value = {
    facilityname: '',
    facilitytype: '',
    FacilityImage: '',
    FacilityIntroduction: '',
    Status: '',
    serviceTime: '',
    equipmentStatus: '',
    parkingSpaces: '',
    chargingPiles: '',
    businessInfo: '',
    contactInfo: '',
    rating: '',
    OtherJson: '',
  }

  // 启动点绘制模式
  sketchViewModel.create('point')
  ElMessage.info('请在地图上点击选择设施位置')

  // 清空临时图层
  sketchLayer.removeAll()
}

// 编辑设施
const editFacility = (feature: __esri.Graphic) => {
  activeTab.value = 'facility'
  editMode.value = 'edit'
  currentFeature = feature

  // 解析OtherJson数据
  let otherData = {}
  try {
    otherData = feature.attributes.OtherJson ? JSON.parse(feature.attributes.OtherJson) : {}
  } catch (e) {
    console.warn('解析OtherJson失败:', e)
  }

  facilityForm.value = {
    facilityname: feature.attributes.facilityname,
    facilitytype: feature.attributes.facilitytype,
    FacilityImage: feature.attributes.FacilityImage,
    FacilityIntroduction: feature.attributes.FacilityIntroduction,
    Status: feature.attributes.Status || '',
    serviceTime: (otherData as any).serviceTime || '',
    equipmentStatus: (otherData as any).equipmentStatus || '',
    parkingSpaces: (otherData as any).parkingSpaces || '',
    chargingPiles: (otherData as any).chargingPiles || '',
    businessInfo: (otherData as any).businessInfo || '',
    contactInfo: (otherData as any).contactInfo || '',
    rating: (otherData as any).rating || '',
    OtherJson: feature.attributes.OtherJson || '',
  }
  dialogVisible.value = true
}

// 删除设施
const deleteFacility = async (feature: __esri.Graphic) => {
  try {
    await facilityLayer.applyEdits({
      deleteFeatures: [feature],
    })
    ElMessage.success('删除成功')
    // 关闭对话框
    dialogVisible.value = false
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 保存设施
const saveFacility = async (formEl: any) => {
  if (!formEl) return
  await formEl.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const formData = facilityForm.value

        if (editMode.value === 'add') {
          if (!tempGraphic) {
            ElMessage.error('请先在地图上选择设施位置')
            return
          }

          // 构建OtherJson数据
          const otherData: any = {}
          if (formData.facilitytype === '驿站') {
            otherData.serviceTime = formData.serviceTime
            otherData.equipmentStatus = formData.equipmentStatus
          } else if (formData.facilitytype === '景点') {
            otherData.parkingSpaces = formData.parkingSpaces
            otherData.chargingPiles = formData.chargingPiles
          } else if (formData.facilitytype === '餐饮') {
            otherData.businessInfo = formData.businessInfo
            otherData.contactInfo = formData.contactInfo
            otherData.rating = formData.rating
          }

          const graphic = new Graphic({
            geometry: tempGraphic!.geometry,
            attributes: {
              facilityname: formData.facilityname,
              facilitytype: formData.facilitytype,
              FacilityImage: formData.FacilityImage,
              FacilityIntroduction: formData.FacilityIntroduction,
              Status: formData.Status,
              OtherJson: JSON.stringify(otherData),
            },
          })
          await facilityLayer.applyEdits({
            addFeatures: [graphic],
          })
          ElMessage.success('添加成功')

          // 清空临时图层
          sketchLayer.removeAll()
          tempGraphic = null
        } else {
          // 构建OtherJson数据
          const otherData: any = {}
          if (formData.facilitytype === '驿站') {
            otherData.serviceTime = formData.serviceTime
            otherData.equipmentStatus = formData.equipmentStatus
          } else if (formData.facilitytype === '景点') {
            otherData.parkingSpaces = formData.parkingSpaces
            otherData.chargingPiles = formData.chargingPiles
          } else if (formData.facilitytype === '餐饮') {
            otherData.businessInfo = formData.businessInfo
            otherData.contactInfo = formData.contactInfo
            otherData.rating = formData.rating
          }

          const graphic = new Graphic({
            geometry: currentFeature!.geometry,
            attributes: {
              ...currentFeature!.attributes,
              facilityname: formData.facilityname,
              facilitytype: formData.facilitytype,
              FacilityImage: formData.FacilityImage,
              FacilityIntroduction: formData.FacilityIntroduction,
              Status: formData.Status,
              OtherJson: JSON.stringify(otherData),
            },
          })
          await facilityLayer.applyEdits({
            updateFeatures: [graphic],
          })
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        isAdding.value = false
        isDrawing.value = false
      } catch (error) {
        console.log(error)
        ElMessage.error(editMode.value === 'add' ? '添加失败' : '更新失败')
      }
    }
  })
}

// 对话框标题
const dialogTitle = computed(() => {
  if (activeTab.value === 'facility') {
    return editMode.value === 'add' ? '添加设施' : '编辑设施'
  }
})

// 根据设施类型获取字段显示状态
const shouldShowField = (facilitytype: string, fieldType: string) => {
  switch (facilitytype) {
    case '驿站':
      return ['name', 'image', 'serviceTime', 'equipmentStatus'].includes(fieldType)
    case '景点':
      return ['name', 'image', 'introduction', 'parkingSpaces', 'chargingPiles'].includes(fieldType)
    case '餐饮':
      return ['name', 'businessInfo', 'contactInfo', 'rating'].includes(fieldType)
    default:
      return false
  }
}


onMounted(async () => {
  view.container = mapContainer.value as HTMLDivElement

  view.ui.add('tools-container', 'top-right')

  // 初始化SketchViewModel
  sketchViewModel = new SketchViewModel({
    view: view,
    layer: sketchLayer,
    pointSymbol: pointSymbol,
    polylineSymbol: roadSymbol,
  })

  // 监听绘图完成事件
  sketchViewModel.on('create', (event) => {
    if (event.state === 'complete' && isDrawing.value) {
      // 保存临时图形
      tempGraphic = event.graphic

      // 显示表单对话框
      dialogVisible.value = true
      isDrawing.value = false
    }
  })



  // 点击事件处理
  view.on('click', async (event) => {
    // 当不在绘图模式时，检查是否点击了设施或道路
    if (!isDrawing.value && !isAdding.value) {
      if (activeTab.value === 'facility') {
        // 检查是否点击了设施
        view.hitTest(event).then((response) => {
          const results = response.results

          // 查找点击的设施图形
          const facilityGraphic = results.find((result) => {
            return 'graphic' in result && (result as any).graphic.layer === facilityLayer
          })

          if (facilityGraphic) {
            // 获取点击的设施图形
            const graphic = (facilityGraphic as any).graphic

            // 直接打开编辑模式
            editFacility(graphic)
          }
        })
      }
    }
  })
})
</script>

<template>
  <div class="management-container">
    <div ref="mapContainer" class="map-view"></div>

    <!-- 功能面板 -->
    <div class="control-panel" id="tools-container">
      <h3 class="panel-title">设施与道路管理</h3>

      <!-- 切换标签 -->
      <div class="tab-container">
        <el-radio-group v-model="activeTab" size="large">
          <el-radio-button label="facility">设施管理</el-radio-button>
          <el-radio-button label="road">道路管理</el-radio-button>
        </el-radio-group>
      </div>

      <!-- 设施管理面板 -->
      <div v-if="activeTab === 'facility'" class="tab-content">
        <el-button type="primary" @click="addFacility" style="width: 100%"> 添加设施 </el-button>
        <div v-if="isDrawing" class="drawing-tip">
          <el-alert title="请在地图上点击选择设施位置" type="info" :closable="false" show-icon />
        </div>
      </div>

      <!-- 道路管理面板 -->
      <div v-if="activeTab === 'road'" class="tab-content">
        <div class="info-tip">
          <el-alert title="道路查看模式" type="info" :closable="false" show-icon />
        </div>
      </div>
    </div>

    <!-- 表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <template #header>
        <div class="dialog-header">
          <span>{{ dialogTitle }}</span>
          <el-button
            v-if="editMode === 'edit'"
            type="danger"
            :icon="Delete"
            circle
            size="small"
            @click="deleteFacility(currentFeature!)"
          />
        </div>
      </template>

      <!-- 设施表单 -->
      <el-form
        v-if="activeTab === 'facility'"
        ref="facilityFormRef"
        :model="facilityForm"
        :rules="facilityRules"
        label-width="100px"
      >
        <!-- 名称字段 - 所有类型都显示 -->
        <el-form-item label="名称" prop="facilityname">
          <el-input v-model="facilityForm.facilityname" />
        </el-form-item>

        <!-- 设施类型选择 -->
        <el-form-item label="设施类型" prop="facilitytype">
          <el-select
            v-model="facilityForm.facilitytype"
            placeholder="请选择设施类型"
            style="width: 100%"
          >
            <el-option
              v-for="item in facilitytypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 图片字段 - 驿站和景点显示 -->
        <el-form-item v-if="shouldShowField(facilityForm.facilitytype, 'image')" label="图片">
          <el-upload
            class="image-upload"
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleImageUpload"
          >
            <el-button type="primary">选择图片</el-button>
          </el-upload>
          <div v-if="facilityForm.FacilityImage" class="image-preview">
            <img :src="facilityForm.FacilityImage" alt="设施照片" />
          </div>
        </el-form-item>

        <!-- 驿站专用字段 -->
        <template v-if="facilityForm.facilitytype === '驿站'">
          <el-form-item label="服务时间">
            <el-input v-model="facilityForm.serviceTime" placeholder="如：24小时" />
          </el-form-item>
          <el-form-item label="设备状态">
            <el-input v-model="facilityForm.equipmentStatus" placeholder="如：正常/维修中/故障" />
          </el-form-item>
        </template>

        <!-- 景点专用字段 -->
        <template v-if="facilityForm.facilitytype === '景点'">
          <el-form-item label="介绍">
            <el-input v-model="facilityForm.FacilityIntroduction" type="textarea" :rows="3" placeholder="请输入景点介绍" />
          </el-form-item>
          <el-form-item label="车位余量">
            <el-input v-model="facilityForm.parkingSpaces" placeholder="如：50个" />
          </el-form-item>
          <el-form-item label="充电桩数量">
            <el-input v-model="facilityForm.chargingPiles" placeholder="如：10个" />
          </el-form-item>
        </template>

        <!-- 餐饮专用字段 -->
        <template v-if="facilityForm.facilitytype === '餐饮'">
          <el-form-item label="营业信息">
            <el-input v-model="facilityForm.businessInfo" type="textarea" :rows="2" placeholder="如：周一至周日 9:00-21:00" />
          </el-form-item>
          <el-form-item label="联系方式">
            <el-input v-model="facilityForm.contactInfo" placeholder="如：电话、微信等" />
          </el-form-item>
          <el-form-item label="评分等级">
            <el-select v-model="facilityForm.rating" placeholder="请选择评分" style="width: 100%">
              <el-option label="⭐" value="1" />
              <el-option label="⭐⭐" value="2" />
              <el-option label="⭐⭐⭐" value="3" />
              <el-option label="⭐⭐⭐⭐" value="4" />
              <el-option label="⭐⭐⭐⭐⭐" value="5" />
            </el-select>
          </el-form-item>
        </template>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveFacility($refs.facilityFormRef)"> 确定 </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.management-container {
  height: 100%;
  width: 100%;
  position: relative;
}

.map-view {
  width: 100%;
  height: 100%;
}

.control-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 1000;
  background: rgba(255, 255, 255, 0.9);
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  width: 280px;
}

.panel-title {
  margin-top: 0;
  margin-bottom: 15px;
  color: #409eff;
  font-size: 18px;
  text-align: center;
}

.tab-container {
  margin-bottom: 15px;
  display: flex;
  justify-content: center;
}

.tab-content {
  margin-top: 10px;
}

.image-preview {
  margin-top: 10px;
  max-width: 200px;
}

.image-preview img {
  width: 100%;
  height: auto;
  border-radius: 4px;
}

.drawing-tip {
  margin-top: 10px;
  width: 100%;
}

.dialog-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}
</style>
